import { fetchWpPostById, BlogPost } from '../api/detail/service'
import { fetchWpPosts } from '../api/articles/service'


// 服务端直接从数据库获取数据的函数
export async function GetWpBlogs(page = 1, pageSize = 10) {
  try {
    const result = await fetchWpPosts(page, pageSize)
    const totalPages = Math.ceil(result.total / pageSize)

    return {
      blogs: result.data,
      pagination: {
        currentPage: page,
        totalPages: Math.ceil(result.total / pageSize),
        hasNextPage: page < totalPages,
        hasPrevPage: page > 1,
      },
    }
  } catch (error) {
    console.error('获取博客数据失败:', error)
    // 返回默认值以防数据库查询失败
    return {
      blogs: [],
      pagination: {
        currentPage: 1,
        totalPages: 0,
        hasNextPage: false,
        hasPrevPage: false,
      }
    }
  }
}

export interface BlogsBody {
  page?: number
  pageSize?: number
}

// 删除热门文章
export async function deleteHotArticle(id: number) {
  const response = await fetch('/api/hot-articles', {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ id })
  })
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`)
  }
  const result = await response.json()
  return result
}

/**
 * 服务端获取 WordPress 文章详情
 */
export async function getWpBlogById(id: string): Promise<BlogPost | null> {
  try {
    return await fetchWpPostById(id)
  } catch (error) {
    console.error('获取文章详情失败:', error)
    throw error
  }
}